package com.ruoyi.web.controller.distribution;

import cn.distribution.officeManager.entity.dao.OfficeManagerDAO;
import cn.distribution.officeManager.service.OfficeService;
import cn.distribution.groupManager.entity.dao.GroupManagerDAO;
import cn.distribution.groupManager.entity.vo.GroupManagerVO;
import cn.distribution.groupManager.service.GroupManagerService;
import cn.distribution.messagesManager.entity.dao.MessagesManagerDAO;
import cn.distribution.messagesManager.service.MessagesManagerService;
import cn.distribution.personManager.entity.vo.PersonManagerVO;
import cn.distribution.personManager.service.PersonManagerService;
import cn.distribution.projectManager.entity.dao.ProjectDAO;
import cn.distribution.projectManager.service.ProjectService;
import cn.distribution.receiptManager.entity.dao.ReceiptDAO;
import cn.distribution.receiptManager.entity.vo.ReceiptVO;
import cn.distribution.receiptManager.service.ReceiptService;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.ServerConfig;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhengminjie
 */
@RestController
@RequestMapping("/distribution/excelManager")
public class ExcelManagerController extends BaseController {
    protected final Logger logger = LoggerFactory.getLogger(GroupManagerController.class);

    @Autowired
    private ProjectService projectService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private GroupManagerService groupManagerService;

    @Autowired
    private PersonManagerService personManagerService;

    @Autowired
    private ReceiptService receiptService;

    @Autowired
    private MessagesManagerService messagesManagerService;

    @GetMapping("/searchProject")
    public TableDataInfo searchGroupList(ProjectDAO projectDAO) {
        List<ProjectDAO> projectDAOList;
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        projectDAOList = this.projectService.list();
        List<ProjectDAO> projectList = new ArrayList<>();
        if(projectDAO.getProjectName()!=null && !Objects.equals(projectDAO.getProjectName(), "")){
            for(ProjectDAO projectDAO1:projectDAOList){
                if(projectDAO1.getUserId().equals(userId) && Objects.equals(projectDAO1.getProjectName(), projectDAO.getProjectName()) && projectDAO1.getDeleteFlag()!=1 ){
                    return getDataTable(Collections.singletonList(projectDAO1));
                }
            }
            return getDataTable(projectList);
        }
        projectDAOList.removeIf(project -> !userId.equals(project.getUserId()) || project.getDeleteFlag() == 1);

        // 处理分页问题
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        int num = projectDAOList.size();
        if(pageNum != null && pageSize != null) {
            projectDAOList = projectDAOList.stream()
                    .skip((pageNum - 1) * pageSize)
                    .limit(pageSize)
                    .collect(Collectors.toList());
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(projectDAOList);
        rspData.setTotal(num);
        logger.info(projectDAOList.toString());
        return rspData;
    }


    @PostMapping("/addProject")
    public AjaxResult addProject(@RequestBody ProjectDAO projectDAO){
        ProjectDAO project = new ProjectDAO();
        project.setProjectName(projectDAO.getProjectName());
        project.setProjectSummary(projectDAO.getProjectSummary());
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        project.setUserId(userId);
        this.projectService.save(project);
        return AjaxResult.success("添加项目成功");
    }

    @GetMapping("/Delete")
    public AjaxResult Delete(Long projectId){
        ProjectDAO project = this.projectService.getById(projectId);
        project.setDeleteFlag(1);
        this.projectService.updateById(project);
        return AjaxResult.success("删除项目成功");
    }

    @PostMapping("/sendExcel")
    public AjaxResult sendExcel(@RequestBody ReceiptVO receiptVO){
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        // 将项目删除标记置为2 该项目不能被删除
        ProjectDAO projectDAO = this.projectService.getById(receiptVO.getProjectId());
        projectDAO.setDeleteFlag(2);
        this.projectService.updateById(projectDAO);
        //根据群号分发群内每一个人
        List<PersonManagerVO> personManagerVOList = this.personManagerService.searchMember(receiptVO.getGroupId(),userId," ");
        for(PersonManagerVO personManagerVO:personManagerVOList){
            if(!personManagerVO.getUserId().equals(userId)) {
                ReceiptDAO receiptDAO = new ReceiptDAO();
                //分发多个列表
                List<Long> officeList = receiptVO.getOfficeList();
                receiptDAO.setProjectId(receiptVO.getProjectId());
                receiptDAO.setReceiptId(personManagerVO.getUserId());
                receiptDAO.setSendId(userId);
                receiptDAO.setGroupId(receiptVO.getGroupId());
                receiptDAO.setIfPublic(receiptVO.getIfPublic());
                receiptDAO.setCreateTime(new Date());
                receiptDAO.setState("未读");
                for (Long office : officeList) {
                    receiptDAO.setOfficeId(office);
                    //如果是私发就将表格数据内容进行解析
                    if (!receiptVO.getIfPublic()) {
                        String filePath = System.getProperty("user.dir") + "\\" + this.officeService.getById(office).getOfficePath();
                        File file = new File(filePath);
                        String fileName = file.getName();
                        try {
                            if (fileName.charAt(fileName.length() - 1) == 's') {
                                HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));
                                HSSFSheet sheet = workbook.getSheetAt(0);
                                HSSFRow titleRow = sheet.getRow(0);
                                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                                    HSSFRow row = sheet.getRow(i);
                                    HSSFCell cell = row.getCell(this.officeService.getById(office).getExcelColumn() - 1);
                                    cell.setCellType(CellType.STRING);
                                    StringBuilder dataContent = new StringBuilder();
                                    if (personManagerVO.getUserNumber() != null && cell.getStringCellValue().equals(personManagerVO.getUserNumber().toString())) {
                                        for (int j = 0; j < row.getLastCellNum(); j++) {
                                            dataContent.append(titleRow.getCell(j)).append(":");
                                            dataContent.append(row.getCell(j)).append(",");
                                        }
                                        dataContent = new StringBuilder(dataContent.substring(0, dataContent.length() - 1));
                                        receiptDAO.setDataContent(dataContent.toString());
                                        this.receiptService.save(receiptDAO);
                                        // 写入一条消息
                                        String s = "收到来自" + this.groupManagerService.getNameById(receiptVO.getGroupId()) +"群的"+this.officeService.getById(office).getOfficeName()+"表格";
                                        MessagesManagerDAO messagesManagerDAO = new MessagesManagerDAO();
                                        messagesManagerDAO.setReceiptId((long) this.receiptService.count());
                                        messagesManagerDAO.setUserName(personManagerVO.getUserName());
                                        messagesManagerDAO.setMessageType(Long.parseLong("0"));
                                        messagesManagerDAO.setMessageContent("你有一份新表格信息");
                                        messagesManagerDAO.setContent(s);
                                        messagesManagerDAO.setState(false);
                                        messagesManagerDAO.setCreateTime(new Date());
                                        this.messagesManagerService.save(messagesManagerDAO);
                                        break;
                                    }
                                }
                            } else {
                                XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file));
                                XSSFSheet sheet = workbook.getSheetAt(0);
                                XSSFRow titleRow = sheet.getRow(0);
                                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                                    XSSFRow row = sheet.getRow(i);
                                    XSSFCell cell = row.getCell(this.officeService.getById(office).getExcelColumn() - 1);
                                    cell.setCellType(CellType.STRING);
                                    StringBuilder dataContent = new StringBuilder();
                                    if (personManagerVO.getUserNumber() != null && cell.getStringCellValue().equals(personManagerVO.getUserNumber().toString())) {
                                        for (int j = 0; j < row.getLastCellNum(); j++) {
                                            dataContent.append(titleRow.getCell(j)).append(":");
                                            dataContent.append(row.getCell(j)).append(",");
                                        }
                                        dataContent = new StringBuilder(dataContent.substring(0, dataContent.length() - 1));
                                        receiptDAO.setDataContent(dataContent.toString());
                                        this.receiptService.save(receiptDAO);
                                        // 写入一条消息
                                        String s = "收到来自" + this.groupManagerService.getNameById(receiptVO.getGroupId()) +"群的"+this.officeService.getById(office).getOfficeName()+"表格";
                                        MessagesManagerDAO messagesManagerDAO = new MessagesManagerDAO();
                                        messagesManagerDAO.setUserName(personManagerVO.getUserName());
                                        messagesManagerDAO.setReceiptId((long) this.receiptService.count());
                                        messagesManagerDAO.setMessageType(Long.parseLong("0"));
                                        messagesManagerDAO.setMessageContent("你有一份新表格信息");
                                        messagesManagerDAO.setContent(s);
                                        messagesManagerDAO.setState(false);
                                        messagesManagerDAO.setCreateTime(new Date());
                                        this.messagesManagerService.save(messagesManagerDAO);
                                        break;
                                    }
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        this.receiptService.save(receiptDAO);
                        // 写入一条消息
                        String s = "收到来自" + this.groupManagerService.getNameById(receiptVO.getGroupId()) +"群的"+this.officeService.getById(office).getOfficeName()+"表格";
                        MessagesManagerDAO messagesManagerDAO = new MessagesManagerDAO();
                        messagesManagerDAO.setUserName(personManagerVO.getUserName());
                        messagesManagerDAO.setMessageType(Long.parseLong("0"));
                        messagesManagerDAO.setReceiptId((long) this.receiptService.count());
                        messagesManagerDAO.setMessageContent("你有一份新表格信息");
                        messagesManagerDAO.setContent(s);
                        messagesManagerDAO.setState(false);
                        messagesManagerDAO.setCreateTime(new Date());
                        this.messagesManagerService.save(messagesManagerDAO);
                    }
                }
            }
        }
        return AjaxResult.success("表格已分发");
    }

    /**
     * 上传到服务器
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(@RequestParam("excel_column")String excelColumn,MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = System.getProperty("user.dir")+"\\office-manager\\src\\main\\resources\\Excel";
            String savePath = "office-manager/src/main/resources/Excel";
            // 上传并返回新文件名称
            String path = FileUploadUtils.uploadExcel(filePath,savePath,file);
            String url = serverConfig.getUrl()+ "/" + path;
            String fileName = file.getName();
            fileName = fileName.substring(0,fileName.lastIndexOf("."));
            OfficeManagerDAO officeManagerDAO = new OfficeManagerDAO();
            officeManagerDAO.setType(0);
            officeManagerDAO.setOfficePath(path);
            officeManagerDAO.setOfficeName(fileName);
            officeManagerDAO.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
            officeManagerDAO.setExcelColumn(Integer.valueOf(excelColumn));
            officeService.save(officeManagerDAO);
            AjaxResult ajax = AjaxResult.success("表格上传成功");
            ajax.put("fileName", file.getOriginalFilename());
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("/excelList")
    public TableDataInfo excelList(OfficeManagerDAO officeManagerDAO) {
        List<OfficeManagerDAO> officeManagerDAOList;
        officeManagerDAOList = this.officeService.list();
        officeManagerDAOList.removeIf(office -> office.getType() == 1);
        logger.info(officeManagerDAOList.toString());
        return getDataTable(officeManagerDAOList);
    }

    @GetMapping("/getGroupList")
    public TableDataInfo getGroupList(GroupManagerDAO groupManagerDAO) {
        List<GroupManagerVO> groupManagerVOList;
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        groupManagerVOList = this.groupManagerService.getGroup(userId,null,"");
        logger.info(groupManagerVOList.toString());
        return getDataTable(groupManagerVOList);
    }

    @GetMapping("/checkExcel")
    public TableDataInfo checkExcel(Long projectId) {
        List<ReceiptVO> receiptVOList = this.receiptService.getIdName(projectId);
        return getDataTable(receiptVOList);
    }

    @GetMapping("/Change")
    public TableDataInfo Change(Long projectId, Long officeId) {
        Map<String, Long> map = new HashMap<String, Long>();
        Long count = this.receiptService.sendCount(officeId, projectId);
        map.put("send",count);
        Long unRead = this.receiptService.unReadCount(projectId, officeId);
        map.put("unRead",unRead);
        Long agree = this.receiptService.agreeCount(projectId, officeId);
        map.put("agree",agree);
        Long refuse = this.receiptService.refuseCount(projectId, officeId);
        map.put("refuse",refuse);
        return getDataTable(Collections.singletonList(map));
    }
}
